<script setup lang="ts" name="TallyInForm">
import { onMounted, reactive, ref, watch } from "vue";
import SelectPosition from "@/components/SelectInfo/SelectPosition.vue";
import SelectPackageType from "@/components/SelectInfo/SelectPackageType.vue";
import { useBillInfo } from "@/store/bill-info";
import { useEditOstInfo } from "@/store/edit-ost-info";
import SelectStorage from "@/components/SelectInfo/SelectStorage.vue";
import BigNumber from "bignumber.js";
import { showFailToast } from "vant";
import { isNumeric } from "vant/es/utils";
import YardMapV2 from "@/components/TallyType/YardMapV2.vue";
import type { PackageTypeData, PositionData, StorageData } from "@/utils/interface";

const billInfo = ref({} as any);
const emit = defineEmits(["result"]);

const perTon = ref(0);

const formData = reactive({
  tallyTon: "",
  tallyPiece: "",
  positionInfo: {} as PositionData,
  spot: "",
  areaCode: "",
  tallyPackageType: "",
  tallyPackageTypeName: "",
  storageAreaId: "",
  storageAreaName: "",
  storagePositionId: "",
  storagePositionName: "",
  goodsPositionId: ""
});

const planPieceTon = ref("");
const storagePieceTon = ref("");
const billInfoStore = useBillInfo();
const editOstInfoStorage = useEditOstInfo();

const validator = (val: any) => isNumeric(val);
const showSelectPackageTypePopup = ref(false);
const showSelectPositionPopup = ref(false);
const isSpotSelect = ref("Y");
const showSelectStoragePopup = ref(false);

onMounted(() => {
  init();
});
billInfoStore.$subscribe(() => {
  init();
});
function init() {
  billInfo.value = billInfoStore.billInfo;

  if (!editOstInfoStorage.editOstInfo.tallyPackageType) {
    formData.tallyPackageType = billInfo.value.packageType;
    formData.tallyPackageTypeName = billInfo.value.packageTypeName;

    if (formData.tallyPackageType === "BU") {
      formData.tallyPiece = "0";
      formData.tallyTon = "0";
    }
  }

  planPieceTon.value = billInfo.value?.piece + "/" + billInfo.value?.ton;
  storagePieceTon.value =
    billInfo.value?.storagePiece + "/" + billInfo.value?.storageTon;
  if (billInfo.value.piece !== 0) {
    const ton = new BigNumber(billInfo.value.ton);
    const piece = new BigNumber(billInfo.value.piece);
    perTon.value = ton.div(piece).toNumber();
  }
}
// 返回表单结果
watch(
  () => formData,
  newValue => {
    emit("result", newValue);
  },
  { immediate: true, deep: true }
);
// 填写件数算吨数
function setPerTon() {
  billInfo.value = billInfoStore.billInfo;
  if (billInfo.value.transportBillId && billInfo.value.piece !== 0) {
    const ton = new BigNumber(billInfo.value.ton);
    const piece = new BigNumber(billInfo.value.piece);
    perTon.value = ton.div(piece).toNumber();
  }
}
function setTon() {
  setPerTon();
  if (formData.tallyPiece && perTon.value) {
    formData.tallyTon = new BigNumber(formData.tallyPiece as string)
      .times(perTon.value)
      .toString();
  }
}
// 改变重垛清空spot值
watch(
  () => isSpotSelect.value,
  () => {
    formData.spot = "";
  },
  { immediate: true, deep: true }
);
// 编辑时初始化
watch(
  () => editOstInfoStorage.editOstInfo,
  newValue => {
    if (newValue.affectStorageId !== "") {
      isSpotSelect.value = "Y";
      formData.spot = newValue.spot;
    }
    formData.positionInfo = {
      id: newValue.storagePositionId,
      name: newValue.storagePositionName,
      areaId: newValue.storageAreaId,
      code: newValue.areaCode,
      areaName: newValue.storageAreaName,
      storageId: newValue.affectStorageId
    };
    formData.tallyTon = newValue.tallyTon;
    formData.tallyPiece = newValue.tallyPiece;
    formData.spot = newValue.spot;
    formData.tallyPackageType = newValue.tallyPackageType;
    formData.tallyPackageTypeName = newValue.tallyPackageTypeName;
    formData.storageAreaId = newValue.storageAreaId;
    formData.storageAreaName = newValue.storageAreaName;
    formData.storagePositionId = newValue.storagePositionId;
    formData.storagePositionName = newValue.storagePositionName;
    formData.goodsPositionId = newValue.goodsPositionId;
  },
  { immediate: true }
);

const isSelectPackageTypeOpen = (value: boolean) => {
  showSelectPackageTypePopup.value = value;
};
const selectedPackageType = (value: PackageTypeData) => {
  formData.tallyPackageType = "";
  formData.tallyPackageTypeName = "";
  formData.tallyPackageType = value.customsPackageCode;
  formData.tallyPackageTypeName = value.packInfo;
};

const isSelectPositionOpen = (value: boolean) => {
  showSelectPositionPopup.value = value;
};
const selectedPosition = (value: PositionData) => {
  formData.positionInfo = {} as PositionData;
  formData.storagePositionName = "";
  formData.positionInfo = value;

  formData.storageAreaId = value.areaId;
  formData.storageAreaName = value.areaName;
  formData.storagePositionId = value.id;
  formData.storagePositionName = value.name;
  formData.areaCode = value.code;
};

const isSelectStorageOpen = (value: boolean) => {
  showSelectStoragePopup.value = value;
};
const selectedStorage = (res: StorageData) => {
  formData.spot = res.spot;
  formData.tallyPackageType = res.packageType;
  formData.tallyPackageTypeName = res.packageTypeName;
  formData.tallyPiece = String(res.piece);
  formData.tallyTon = res.ton;
  formData.goodsPositionId = res.goodsPositionId;
  formData.areaCode = res.areaCode;
};
const validate = () => {};
const onFailed = (value: any) => {
  showFailToast("请检查表单");
};

const showYard = ref(false);

const onSelectedArea = (e: any) => {
  console.log(e);
  showYard.value = false;
  if (isSpotSelect.value) {
    formData.spot = e.names;
  }
  formData.goodsPositionId = e.id;
};
</script>

<template>
  <div
    id="tallyInForm"
    class="w-full flex flex-col bg-white py-[10px] px-[15px] rounded-lg mt-3"
  >
    <div class="w h-[40px] flex justify-between">
      <div class="flex h w items-center font-bold">入库</div>
    </div>
    <form @submit="validate" @failed="onFailed">
      <van-cell-group :border="false">
        <van-field
          readonly
          v-model="planPieceTon"
          name="planPieceTon"
          label="计划件吨"
        />
        <van-field
          readonly
          v-model="storagePieceTon"
          name="storagePieceTon"
          label="库存件吨"
        />
        <van-field
          readonly
          name="position"
          label="货场"
          placeholder="请选择货场"
          is-link
          v-model="formData.storagePositionName"
          @click="showSelectPositionPopup = true"
          :rules="[{ required: true, message: '请选择货场' }]"
        >
          <template #label> 货场<span class="xing">*</span> </template>
        </van-field>
        <van-popup
          v-model:show="showSelectPositionPopup"
          position="bottom"
          round
          duration="0"
          :style="{ height: 'auto' }"
        >
          <SelectPosition
            :position="{
              value: formData.positionInfo.id,
              text: formData.positionInfo.name
            }"
            @isOpen="isSelectPositionOpen"
            @selectedPosition="selectedPosition"
          ></SelectPosition>
        </van-popup>
        <van-field
          name="timeSpace"
          label="重垛"
          :rules="[{ required: true, message: '请选择是否重垛' }]"
        >
          <template #input>
            <van-radio-group
              shape="dot"
              v-model="isSpotSelect"
              direction="horizontal"
            >
              <van-radio name="Y" icon-size="18px">是</van-radio>
              <van-radio name="N" icon-size="18px">否</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          v-if="isSpotSelect === 'N'"
          name="position"
          label="货位"
          v-model="formData.spot"
          placeholder="请填写货位并绘制地图"
          :rules="[{ required: true, message: '请填写货位' }]"
        >
          <template #label> 货位<span class="xing">*</span> </template>
          <template #button>
            <van-button size="small" type="primary" @click="showYard = true"
              >绘图</van-button
            >
          </template>
        </van-field>
        <van-field
          v-if="isSpotSelect === 'Y'"
          name="position"
          label="货位"
          readonly
          v-model="formData.spot"
          @click="showSelectStoragePopup = true"
          placeholder="请选择货位并绘制地图"
          :rules="[{ required: true, message: '请选择货位' }]"
        >
          <template #label> 货位<span class="xing">*</span> </template>
        </van-field>
        <van-popup
          v-model:show="showSelectStoragePopup"
          position="bottom"
          round
          duration="0"
          class="bg-slate-400 h-[calc(100vh-100px)]"
        >
          <SelectStorage
            :positionInfo="formData.positionInfo"
            :storageId="formData.positionInfo.storageId"
            :positionId="formData.positionInfo.id"
            :transportBillId="billInfo.transportBillId"
            @isOpen="isSelectStorageOpen"
            @selectedStorage="selectedStorage"
          ></SelectStorage>
        </van-popup>
        <!--      <van-field-->
        <!--         -->
        <!--        name="position"-->
        <!--        label="规格/件号"-->
        <!--        placeholder="如需要请填写"-->
        <!--      />-->
        <van-field
          readonly
          name="tallyPackageType"
          is-link
          placeholder="请选择包装"
          v-model="formData.tallyPackageTypeName"
          @click="showSelectPackageTypePopup = true"
          :rules="[{ required: true, message: '请选择包装' }]"
        >
          <template #label> 包装<span class="xing">*</span> </template>
        </van-field>
        <van-popup
          v-model:show="showSelectPackageTypePopup"
          position="bottom"
          round
          duration="0"
          :style="{ height: 'auto' }"
        >
          <SelectPackageType
            :packageType="{
              value: formData.tallyPackageType,
              text: formData.tallyPackageTypeName
            }"
            @isOpen="isSelectPackageTypeOpen"
            @selectedPackageType="selectedPackageType"
          ></SelectPackageType>
        </van-popup>
        <van-field
          name="piece"
          v-model="formData.tallyPiece"
          label="理货件数"
          placeholder="请输入件数"
          :rules="[{ validator, message: '请输入件数' }]"
        >
          <template #label> 理货件数<span class="xing">*</span> </template>
        </van-field>
        <van-field
          name="ton"
          :border="false"
          v-model="formData.tallyTon"
          @focus="setTon"
          label="理货吨数"
          placeholder="请输入吨数"
          :rules="[{ validator, message: '请输入吨数' }]"
        >
          <template #label> 理货吨数<span class="xing">*</span> </template>
        </van-field>
      </van-cell-group>
    </form>
    <yard-map-v2
      v-if="showYard"
      :positionInfo="formData.positionInfo"
      :goodsPositionId="formData.goodsPositionId"
      @closeMap="showYard = false"
      @saved="onSelectedArea"
    ></yard-map-v2>
  </div>
</template>

<style scoped>
.header {
  background: linear-gradient(144deg, rgba(64, 169, 255, 1) 6%, #f7f8fa 6%);
}
</style>
